<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <div style="margin-bottom: 10px;">
            <span style="font-weight: bold">订单状态：</span>
            <a-checkable-tag style="font-size: 14px;margin: 5px;padding: 5px" v-for="(item,index) in this.orderStatusList"
                             :key="index" v-model:checked="item.checkedValue"
                             @change="onChangeOrderStatus(item.key,item.itemValue)">{{item.itemText}}
            </a-checkable-tag>
          </div>
        </a-row>

        <!--<a-row :gutter="24">
          <a-col :span="6">
            <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplier">
              <a-select
                show-search
                :allowClear="true"
                placeholder="请选择供应商"
                option-filter-prop="children"
                v-model="queryParam.supplierName"
                style="width: 100%"
                :filter-option="filterOptionSupplier"
                @change="changeSupplier">
                <a-select-option :value="item.supplierName" v-for="(item,index) in supplierData" :key="index">
                  {{item.supplierName}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="depositoryName">
              <a-select
                show-search
                :allowClear="true"
                placeholder="请选择仓库"
                option-filter-prop="children"
                v-model="queryParam.depositoryName"
                style="width: 100%"
                :filter-option="filterOptionDepository"
                @change="changeDepository">
                <a-select-option :value="item.depositoryName" v-for="(item,index) in depositoryData" :key="index">
                  {{item.depositoryName}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-model-item label="入库状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="supplier">
              <a-select placeholder="请选择" style="width: 100%" v-model="queryParam.beLaidUpStatus" @change="changeBeLaidUpStatus" :allowClear="true">
                <a-select-option value="1">未入库</a-select-option>
                <a-select-option value="2">部分入库</a-select-option>
                <a-select-option value="3">完全入库</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="采购人员">
              <a-tree-select
                style="width: 50%"
                :allowClear="true"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="departListData"
                :replaceFields="dataFields"
                placeholder="请选择部门"
                @change="changeDepart"
              >
              </a-tree-select>
              <span style="margin-left: 1%;margin-right: 1%">&#45;&#45;</span>
              <a-select
                show-search
                :allowClear="true"
                placeholder="请选择采购人员"
                option-filter-prop="children"
                v-model="queryParam.purchasePeople"
                style="width: 30%;"
                :filter-option="filterOptionPurchasePeople"
                @change="changePurchasePeople">
                <a-select-option :value="item.realname" v-for="(item,index) in purchasePeopleData" :key="index">
                  {{item.realname}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
            <a-button type="primary" @click="resetSearch" icon="reload" style="margin-left: 8px">重置</a-button>
          </a-col>
        </a-row>-->
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!--<a-button @click="addPurchaseOrder" type="primary" icon="plus">新增</a-button>-->
      <!--<a-button type="primary" icon="download" @click="handleExportXls('供应链采购订单表')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"
                @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>-->
      <!-- 高级查询区域 -->
      <!--<j-super-query :fieldList="superFieldList" ref="superQueryModal"
                     @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete"/>
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作
          <a-icon type="down"/>
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <!--<div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
        selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>-->

      <div class="list">
        <van-list
          v-model="loading"
          :finished="finished"
          offset="100"
          finished-text="没有更多了"
          @load="onLoadList"
          :immediate-check="false"
        >
          <div
            class="customer-list"
            v-for="(item,i) in dataSource"
            :key="i"
            @click="purchaseOrderDetail(item)"
          >
            <div>
              <div class="name">采购编号：{{ item.purchaseNo || '无' }}</div>
              <div class="contact">
                <span>采购名称：{{ item.purchaseName || '无' }}</span>
              </div>
              <div class="contact">
                <span>供应商：{{ item.supplierName || '无' }}</span>
              </div>
              <div class="contact">
                <span>金额：{{ item.discountedPurchasePrice || 0 }}</span>
              </div>
              <div class="contact">
                <span>订单状态：
                  <a-tag v-if="item.orderStatus === 1">草稿</a-tag>
                  <a-tag color="orange" v-if="item.orderStatus === 2">审批中</a-tag>
                  <a-tag color="green" v-if="item.orderStatus === 3">审批通过</a-tag>
                  <a-tag color="red" v-if="item.orderStatus === 4">未通过</a-tag>
                  <a-tag color="magenta" v-if="item.orderStatus === 5">已撤销</a-tag>
                </span>
                <span style="margin-left: 20px">审批人：{{ item.approvedBy || "无" }}</span>
              </div>
              <div class="contact">
                <span>仓库：{{ item.depositoryName || '无' }}</span>
                <!--<span style="float: right">
                  <a @click="transferFormDetail(item)">详情</a>
                  <a-divider type="vertical" />
                  <a @click="placeOrderRecord(item)">下单记录</a>
                </span>-->
              </div>
              <div class="contact">
                <span>入库状态：
                  <a-tag color="orange" v-if="item.orderStatus === 1">未入库</a-tag>
                  <a-tag color="blue" v-if="item.orderStatus === 2">部分入库</a-tag>
                  <a-tag color="green" v-if="item.orderStatus === 3">完全入库</a-tag>
                </span>
              </div>
            </div>
          </div>
        </van-list>
      </div>

      <!--<a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :customRow="setRow"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onSelectAll:onSelectAll,
          onSelect:onSelect,
          onChange: onSelectChange,
          type:'checkbox'
        }"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <a slot="purchaseNo" @click="purchaseOrderDetail(record)" slot-scope="text,record">{{ text }}</a>

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt=""
               style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="remark" slot-scope="text,record">
          <div class="remarkTxt" :alt="text">
            {{text}}
          </div>
        </span>

        <span slot="action" slot-scope="text, record" >
          <a @click="editPurchaseOrder(record)" v-if="(record.orderStatus == 1 || record.orderStatus == 4) && record.isEditAble == 1">编辑</a>
          <a-divider type="vertical" v-if="(record.orderStatus == 1 || record.orderStatus == 4) && record.isEditAble == 1"/>
          <a @click="purchaseOrderDetail(record)">详情</a>
          <a-divider type="vertical"/>
          <a-popconfirm title="确定撤销吗?" @confirm="() => revoke(record.id)" v-if="record.orderStatus == 1">
            <a>撤销</a>
          </a-popconfirm>
          <a-divider type="vertical" v-if="record.orderStatus == 1 && record.isEditAble == 1"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)" v-if="record.orderStatus == 1 && record.isEditAble == 1">
            <a>删除</a>
          </a-popconfirm>

        </span>

      </a-table>-->
    </div>
    <purchase-order-modal ref="purchaseOrderModal" @ok="modalFormOk"></purchase-order-modal>
    <purchase-order-detail-modal ref="purchaseOrderDetailModal" @ok="modalFormOk"></purchase-order-detail-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import {mixinDevice} from '@/utils/mixin'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import purchaseOrderModal from "./modules/purchaseOrderModal";
  import {getAction,putAction} from "../../../../api/manage";
  import purchaseOrderDetailModal from "./modules/purchaseOrderDetailModal";

  export default {
    name: 'purchaseOrderList',
    mixins: [JeecgListMixin, mixinDevice],
    components: {
      purchaseOrderModal,purchaseOrderDetailModal
    },
    data() {
      return {
        description: '供应链采购订单表管理页面',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: "center",
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '采购编号',
            align: "center",
            dataIndex: 'purchaseNo',
            slots: { title: 'customTitle' },
            width: 200,
            scopedSlots: { customRender: 'purchaseNo' },
          },
          {
            title: '采购名称',
            align: "center",
            dataIndex: 'purchaseName'
          },
          {
            title: '单据日期',
            align: "center",
            dataIndex: 'receiptsTime'
          },
          {
            title: '交货日期',
            align: "center",
            dataIndex: 'deliveryTime'
          },
          {
            title: '供应商',
            align: "center",
            dataIndex: 'supplierName'
          },
          {
            title: '采购人员',
            align: "center",
            dataIndex: 'purchasePeople'
          },
          {
            title: '金额',
            align: "center",
            //dataIndex: 'purchasePrice',
            dataIndex: 'discountedPurchasePrice',
            customRender:function (text) {
              if (text != null && text !== ""){
                return text+"元"
              }else {
                return "-"
              }
            }
          },
          {
            title: '订单状态',
            align: "center",
            dataIndex: 'orderStatus',
            customRender:function (text) {
              switch (text) {
                case 1:
                  return <a-tag>草稿</a-tag>
                  break;
                case 2:
                  return <a-tag color="orange">审批中</a-tag>
                  break;
                case 3:
                  return <a-tag color="green">审批通过</a-tag>
                  break;
                case 4:
                  return <a-tag color="red">未通过</a-tag>
                  break;
                case 5:
                  return <a-tag color="magenta">已撤销</a-tag>
                  break;
              }
            }
          },
          {
            title: '审批人',
            align: "center",
            dataIndex: 'approvedBy'
          },
          {
            title: '仓库',
            align: "center",
            dataIndex: 'depositoryName'
          },
          {
            title:'订单备注',
            align:"center",
            dataIndex: 'remark',
            scopedSlots: { customRender: 'remark' },
          },
          {
            title:'审批原因',
            align:"center",
            dataIndex: 'reason',
            ellipsis: true,
            scopedSlots: { customRender: 'reason' },
          },
          {
            title: '入库状态',
            align: "center",
            dataIndex: 'beLaidUpStatus',
            customRender:function (text) {
              if (text == 1){
                return <a-tag color="orange">未入库</a-tag>
              }else if (text == 2){
                return <a-tag color="blue">部分入库</a-tag>
              }else if(text == 3){
                return <a-tag color="green">完全入库</a-tag>
              }
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            width:200,
            scopedSlots: {customRender: 'action'}
          }
        ],
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        /* 数据源 */
        dataSource:[],
        supplierData: [],   //供应商列表
        depositoryData: [], //仓库列表
        purchasePeopleData:[],  //采购人员列表
        url: {
          list: "/ghSupplychainPurchaseOrder/list",
          delete: "/ghSupplychainPurchaseOrder/delete",
          deleteBatch: "/ghSupplychainPurchaseOrder/deleteBatch",
          exportXlsUrl: "/ghSupplychainPurchaseOrder/exportXls",
          importExcelUrl: "/ghSupplychainPurchaseOrder/importExcel",
          edit: "/ghSupplychainPurchaseOrder/edit",
          getSearchConditionData: "/ghSupplychainPurchaseOrder/getQueryCriteriaData",
          querySupplierList: "/ghSupplychainSupplier/allList",
          queryDepositoryList: "/ghSupplychainDepository/allList",
          queryUserList: "/erp/user/selectUserByDepartId",
          queryDepartTreeList: "/erp/user/selectDepartTreeList",
        },
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        dictOptions: {},
        superFieldList: [],
        orderStatusList:[],   //搜素条件：订单状态
        currentOrderStatus: 0,
        selectedRowKeys: [],
        selectedRows: [],
        dataFields: {
          title: 'departName',
          key: 'id',
          value: 'id',
          children: "children"
        },
        currentDepartId: "",  //当前所选部门
        departListData:[],    //部门列表
        finished: false,
      }
    },
    created() {
      this.initSearchConditionData();
      this.loadDepartTreeListData();
      this.loadSupplierData();
      this.loadDepositoryData();
      this.loadData();
    },
    computed: {
      importExcelUrl: function () {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      revoke(id){
        var that = this;
        let params = {};
        params.id = id;
        params.receiptsType = 1;
        params.orderStatus = 5;
        putAction(this.url.edit,params).then((res =>{
          if (res.success){
            that.$message.success(res.message);
            that.loadData();
          }else {
            that.$message.warning(res.message);
          }
        }))
      },
      //新增采购订单
      addPurchaseOrder(){
        this.$refs.purchaseOrderModal.title = "新增采购订单"
        this.$refs.purchaseOrderModal.addPurchaseOrder();
        this.$refs.purchaseOrderModal.loadSupplierData();
        this.$refs.purchaseOrderModal.loadDepositoryData();
        this.$refs.purchaseOrderModal.loadUserListData();
      },
      //编辑采购订单
      editPurchaseOrder(record){
        this.$refs.purchaseOrderModal.title = "修改采购订单"
        //this.$refs.purchaseOrderModal.currentChoosePersonInCharge = record.purchasePeople;
        this.$refs.purchaseOrderModal.editPurchaseOrder(record);
        this.$refs.purchaseOrderModal.loadSupplierData();
        this.$refs.purchaseOrderModal.loadDepositoryData();
        this.$refs.purchaseOrderModal.loadUserListData();
      },
      //详情
      purchaseOrderDetail(record){
        this.$refs.purchaseOrderDetailModal.title = "采购订单详情";
        this.$refs.purchaseOrderDetailModal.showDetail(record);
      },
      modalFormOk(){
        this.loadData();
      },
      onLoadList(e){
        this.ipagination.current++
        this.loadData(this.ipagination.current)
      },
      loadData(arg) {
        if(!this.url.list){
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
          this.dataSource = []
          this.finished = false;
        }
        var params = this.getQueryParams();//查询条件
        params.receiptsType = 1;
        if (this.currentOrderStatus != null && this.currentOrderStatus != '' && this.currentOrderStatus != 0) {
          params.orderStatus = this.currentOrderStatus;
        }else {
          params.orderStatus = "";
        }
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = [...this.dataSource, ...res.result.records]
            if(res.result.total)
            {
              this.ipagination.total = res.result.total;
            }else{
              this.ipagination.total = 0;
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }else{
            this.$message.warning(res.message)
          }
          if(res.result.records.length<10){
            this.finished = true;
          }
        }).finally(() => {
          this.loading = false
        })
      },
      initSearchConditionData() {
        getAction(this.url.getSearchConditionData).then(res => {
          if (res.success) {
            /*this.receiptsTypeList = res.result.receiptsTypeList;
            this.receiptsDateList = res.result.receiptsDateList;*/
            this.orderStatusList = res.result.orderStatusList;
          }
        })
      },
      //加载用户列表
      loadUserListData() {
        getAction(this.url.queryUserList,{departId:this.currentDepartId}).then((res) => {
          if (res.success) {
            this.purchasePeopleData = res.result.records||res.result;
            this.createByData = res.result.records||res.result;
          }
        })
      },
      //加载供应商
      loadSupplierData(){
        getAction(this.url.querySupplierList).then((res) => {
          if (res.success) {
            this.supplierData = res.result.records||res.result;
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      //加载仓库
      loadDepositoryData(){
        getAction(this.url.queryDepositoryList).then((res) => {
          if (res.success) {
            this.depositoryData = res.result.records||res.result;
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      //订单状态发生变化
      onChangeOrderStatus(key, itemValue){
        for (let i = 0; i < this.orderStatusList.length; i++) {
          if (key == this.orderStatusList[i].key) {
            this.orderStatusList[i].checkedValue = true;
          } else {
            this.orderStatusList[i].checkedValue = false;
          }
        }
        this.currentOrderStatus = itemValue;
        this.loadData(1);
      },
      filterOptionSupplier(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      filterOptionDepository(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      filterOptionPurchasePeople(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      changeSupplier(value){
        this.loadData(1);
      },
      changeDepository(value){
        this.loadData(1);
      },
      changePurchasePeople(value){
        this.loadData(1);
      },
      changeBeLaidUpStatus(value){
        this.loadData(1)
      },
      resetSearch() {
        this.queryParam = {}
        let arr = this.orderStatusList;
        this.orderStatusList = [];
        this.orderStatusList = arr;
        //this.model = {};
        this.loadData(1);
      },
      onSelectAll(selected, selectedRows, changeRows) {
        if(selected) {
          let rows = [...selectedRows]
          this.selectedRows = this.selectedRows.concat(rows)
        } else {
          changeRows.forEach(item => {
            const delIndex = this.selectedRows.findIndex((val) => {
              return val.id === item.id
            })
            this.selectedRows.splice(delIndex, 1)
          })
        }
      },
      onSelect(record, selected) {
        if(selected) {
          this.selectedRows.push(record);
        } else {
          const delIndex = this.selectedRows.findIndex((val) => {
            return val.id === record.id
          })
          this.selectedRows.splice(delIndex,1)
        }
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
      },
      //表格行点击事件
      setRow (record) {
        return {
          on: {
            click: () => {
              let flag = false
              let keys = [];
              keys = this.selectedRowKeys;
              if(keys.indexOf(record.id) >= 0) {
                flag=true
              }
              if(flag){
                keys.splice(keys.findIndex(item => item === record.id), 1)
                this.selectedRows.splice(this.selectedRows.findIndex(item => item === record.id),1)
              } else {
                keys.push(record.id)
                this.selectedRows.push(record);
              }
            }
          }
        }
      },
      //加载部门树形列表
      loadDepartTreeListData(){
        getAction(this.url.queryDepartTreeList).then((res) => {
          if (res.success) {
            this.departListData = res.result.records||res.result;
          }
        })
      },
      changeDepart(value){
        this.currentDepartId = value;
        this.loadUserListData();
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';

  /deep/ .van-dropdown-menu__bar{
    height: 30px;
    box-shadow: none;
    border: 1px solid lightgrey;
    border-radius: 5px;
  }

  .list{
    overflow-y: scroll;
    height:100vh;
  }
  ::-webkit-scrollbar {
    display: none;
  }
  .customer-list {
    align-items: center;
    border-top: 1px solid #d9d9d9;
    /*height: 120px;*/
  }
  .name{
    margin-top: 10px;
    margin-bottom: 5px;
    font-size: 13px;
    color: #161616;
    line-height: normal;
  }
  .contact{
    font-size: 12px;
    color: #a39f9f;
    margin-bottom: 5px;
  }
</style>
<!--
<style scoped>
  @import '~@assets/less/common.less';
  .remarkTxt{
    max-width: 350px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>-->
